package shiyan4;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class Server2 {
    public static void main(String[] args) throws IOException {
        int port1 = 8080;
        int port2 = 8081;
        DatagramSocket socket = new DatagramSocket(port2);
        socket.setBroadcast(true);
        Thread receiveThread = new Thread(new receiveThread(socket));
        receiveThread.setDaemon(true);
        receiveThread.start();

        String msg;
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        while ((msg = in.readLine())!=null) {
            if ("exit".equals(msg)) {break;}
            byte[] buf = msg.getBytes();
            InetAddress address = InetAddress.getByName("127.0.0.1");
            DatagramPacket packet = new DatagramPacket(buf, buf.length, address, port1);
            socket.send(packet);
            System.out.println("已发送广播"+msg);
        }
    }
    static class receiveThread implements Runnable {
        DatagramSocket socket;
        public receiveThread(DatagramSocket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            byte[] buf = new byte[1024];
            while (true) {
                DatagramPacket packet = new DatagramPacket(buf, buf.length);
                try {
                    socket.receive(packet);
                    String s = new String(packet.getData(), 0, packet.getLength());
                    System.out.println("收到来自"+packet.getAddress().getHostAddress()+"的回复"+s);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

            }
        }
    }
}
